!(function(window){
	'use strict';
	// 基础方法
	// 字符串转为对象（包括数组）
	window.strToObject = function ( str )
	{
		var res = null;
		try {
			res = JSON.parse(str);
		} catch(e) {
			 
		}
		if( !res instanceof Object )
		{
			res = null;
		}
		return res;
	}
	// 把字符串用原生方法生成dom对象
	window.parseDom = function(str){
		if(str && str.replace(/\s/g,'')!=''){
			var parentDom =	document.createElement("div");
			parentDom.innerHTML = str;
			return parentDom.childNodes; 
		}else{
			return null;
		}
	}
	// 元素后面插入node
	window.insertAfter = function(newEl, targetEl)
	{
	    var parentEl = targetEl.parentNode;
	            
	    if(parentEl.lastChild == targetEl)
	    {
	        parentEl.appendChild(newEl);
	    }else{
	        parentEl.insertBefore(newEl,targetEl.nextSibling);
	    }            
	}
	//字符串空格去除（去除所有空格、两头空格）
	//删除左右两端的空格
	window.trim = function(str) {　　
		return str.replace(/(^\s*)|(\s*$)/g, '');　　
	}　　
	//删除左边的空格
	window.ltrim = function(str) {　　
		return str.replace(/(^\s*)/g, '');　　
	}　　
	//删除右边的空格
	window.rtrim = function(str) {　　
		return str.replace(/(\s*$)/g, '');　　
	}
	//去除所有空格
	window.strim = function(str) {
		return str.replace(/\s/g, '');
	}
	//字符串计算长度
	window.strlen = function(str) {
		var regch = /[\u4e00-\u9fa5]/;
		var length = 0;
		for(var i = 0; i < str.length; i++) {
			if(regch.test(str.charAt(i)) == true) {
				// 中文为2个字符
				length += 2;
			} else {
				// 英文一个字符
				length += 1;
			}
		}
		return length;
	}
	// 秒的时间转分秒
	window.sec2ms = function(timeR) {
		timeR = timeR || 0;
		var min = Math.ceil(timeR / 60),
			sec = Math.ceil(timeR % 60);
		min = min > 0 && sec > 0 ? min - 1 : min;
		min = min < 10 ? '0' + min : min;
		sec = sec < 10 ? '0' + sec : sec;
		if(sec == 60 && min == 0) {
			return "01:00";
		}
		return min + ":" + sec;
	}
	// 剩余时间计算
	window.leavetime = function(timeR, total) {
		timeR = timeR || timeformat('2017-05-17 00:00:00', 'timestamp');
		total = total || 86400 * 3;
		timeR = timeR / 1000;
		var now = timeformat(0, 'timestamp') / 1000;
		var timec = (timeR + total) - now; // 时间差值
		var day = '',
			hour = '',
			min = '',
			sec = '',
			d = 0,
			h = 0,
			m = 0,
			s = 0;
		if(timec > 86400) {
			d = Math.floor(timec / 86400);
			day = d > 0 ? d + '天' : '';
			timec = timec % 86400;
		}
		if(timec > 3600) {
			h = Math.floor(timec / 3600);
			hour = h > 0 ? h + '小时' : '';
			timec = timec % 3600;
		}
		if(timec > 59) {
			m = Math.floor(timec / 60);
			min = m > 0 ? m + '分钟' : '';
		}
		return day + hour + min;
	}
	// 时间格式化
	window.timeformat = function(str, format, tissue) {
		var myDate = new Date();
		str = (str == 0 || !str || str == 'undefined' || str == NaN) ? myDate.getTime() : str;
		str = (typeof str == 'string') ? 　str.replace(/\-/g, '/') : str;
		(!format || format == '') ? format = 'y-m-d h:i:s': format;
		var nowstamp = parseInt(myDate.getTime() / 1000),
			itemtime = parseInt(str),
			year, m, d, h, i, s;
		if(format == 'timestamp') {
			(str === +str) ? str = str: str = Date.parse(str);
			return str;
		}
		if(itemtime < 10000) {
			//普通时间直接转换
			itemtime = Date.parse(str);
		}
		if(itemtime > 100000000000) {
			itemtime = itemtime / 1000;
		}
		var timebe = nowstamp - itemtime;
		if(tissue && tissue > -1 && tissue < 864000 && timebe < tissue) {
			if(timebe > 86400) {
				//超过1天，按天计算
				return Math.floor(timebe / 86400) + '天前';
			} else if(timebe > 3600) {
				//超过1小时，按小时计算
				return Math.floor(timebe / 3600) + '小时前';
			} else if(timebe > 59) {
				//按分钟计算
				return Math.ceil(timebe / 60) + '分钟前';
			} else {
				return '刚刚';
			}
		} else {
			itemtime = myDate.setTime(itemtime * 1000);
			year = myDate.getFullYear();
			m = (myDate.getMonth() + 1 < 10) ? '0' + (myDate.getMonth() + 1) : myDate.getMonth() + 1;
			d = (myDate.getDate() < 10) ? '0' + (myDate.getDate()) : myDate.getDate();
			h = (myDate.getHours() < 10) ? '0' + (myDate.getHours()) : myDate.getHours();
			i = (myDate.getMinutes() < 10) ? '0' + (myDate.getMinutes()) : myDate.getMinutes();
			s = (myDate.getSeconds() < 10) ? '0' + (myDate.getSeconds()) : myDate.getSeconds();

			return format.replace('y', year).replace('m', m).replace('d', d).replace('h', h).replace('i', i).replace('s', s);
		}
	}
	// 解析url参数
	window.UrlParse = function(){
		this.init();
	}
	window.UrlParse.prototype = {
		init:function(){
			this.urlStr = [window.location.origin+window.location.pathname,window.location.search.substr(1)];
			this.urlStr[1] = this.urlStr[1] ? this.urlStr[1] : '';
			this.pramaStr = this.urlStr[1].split("&") || [];
			this.pramaArr = {};
			this.hashStr = window.location.hash.substr(1) || '';
			for (var i = 0;i < this.pramaStr.length; i++) {
				if(this.pramaStr[i]&&this.pramaStr[i]!=''){
					var spres = this.pramaStr[i].split("=");
					this.pramaArr[spres[0]] = decodeURI(spres[1]);
				}			
			}
			console.log(this)
		},
		getParam:function(key){
			if(key&&key!=''){
				return this.pramaArr[key] || null;
			}else{
				return this.pramaArr;
			}		
		},
		setParam:function(key,value){
			key = key || '';
			value = value || '';
			if(key=='' && value==''){
				return;
			}
			if(value==''){
				delete this.pramaArr[key];
			}else{
				this.pramaArr[key] = decodeURI(value);
			}
			console.log(this)
			this.flushUrl();
		},
		getHash:function(){
			return this.hashStr;
		},
		setHash:function(str){
			if(!str || str.replace(/\s/gi,'')=='' || str.replace(/\s/gi,'') == '#'){
				return;
			}
			window.location.hash = '#'+str;
			this.hashStr = str;
		},
		flushUrl:function(stateObj,title,url){
			stateObj = stateObj || {};
			title = title || document.title;
			url = url || this.urlStr[0];
			var newUrl = this.buildUrl(url);
			history.pushState(stateObj,title,newUrl);
		},
		buildUrl:function(url){
			url = url || this.urlStr[0];
			var newUrl = url+'?';
			for(var i in this.pramaArr){
				newUrl += i && i!='' ? i+'='+encodeURI(this.pramaArr[i])+'&' : '';
			}
			return newUrl.substring(0,newUrl.length-1);
		}
	}

	window.reload = function(url) {
		url = url || null;
		UrlParam.setParam('_hash', 100 * Math.random());
		window.location.href = UrlParam.buildUrl(url);
	}
	// 客户端类型
	window.Agent = function(){
		var ua = window.navigator.userAgent;		
		if(ua.match(/iPhone|iPod/i) != null){
			//iphone
			return 'iphone';
		}
		else if(ua.match(/Android/i) != null){
			//android
			return 'android';
		}
		else if(ua.match(/iPad/i) != null){
			//ipad
			return 'ipad';
		}else{
			return ua;
		}
	}


	// 数字转汉字
	window.num2Txt = function (num){
		var n = num.replace(/[^0-9]/ig,""),
				Num = parseInt(n),
				Nconfig = ["零","一","二","三","四","五","六","七","八","九"],
				config = ["","","十","百","千","万","十","百","千","亿"],
				res = '';
		if(Num>0){
			var l = n.length,NumArr = new Array();
			NumArr = n.split("");
			for(var i= 0; i < l; i++){
				if((NumArr[i] == '0' || NumArr[i] == 0)&&i==l-1){
					continue;
				}
				res +=  NumArr[i] == '0' || NumArr[i] == 0 ? Nconfig[NumArr[i]] : Nconfig[NumArr[i]]+config[l-i];
			}
			res = res.replace(/^一十+(.*?)$/,"十$1");
		}
		if(Num==0){
			res = "零";
		}
		return num.replace('%'+n+'%',res);
	}


	// toast
	window.Toast = function(opt) {
		var that = this;
		that.closemyself();
		this.title = opt.title || '提示';
		this.content = opt.content || '';
		this.btn = opt.btn || [{
			type: 'ok',
			title: '确定',
			callback: false
		}];
		this.toast = $('<div class="tankuang"></div>');
		this.toastMain = this.btn.length == 1 ? $('<div class="tankuang1 tankuang2"></div>') : $('<div class="tankuang1"></div>');
		this.toastTitle = $('<h2>' + this.title + '</h2>');
		this.toastContent = $('<p>' + this.content + '</p>');

		this.BtnBox = $('<div class="bot"></div>');
		this.Btn = [];

		for(var i = 0; i < this.btn.length; i++) {
			this.Btn[i] = this.btn[i].type == 'cancel' ? $('<div class="no">' + this.btn[i].title + '</div>') : $('<div class="ok">' + that.btn[i].title + '</div>');
			this.btn[i].callback = this.btn[i].callback instanceof Function ? this.btn[i].callback : this.closemyself;
			this.Btn[i].attr("index", i);
			this.Btn[i].click(function() {
				that.docall(this);
			});
			this.BtnBox.append(this.Btn[i]);
		}

		this.toastMain.append(this.toastTitle).append(this.toastContent).append(this.BtnBox);
		this.toast.append(this.toastMain);
		$("body").append(this.toast);
		this.init(opt);
	}

	window.Toast.prototype = {
		init: function(opt) {

			this.toast.show();
			console.log(this);
		},
		closemyself: function() {
			closeToast();
		},
		docall: function(item) {
			console.log(item)
			this.btn[$(item).attr('index')].callback();
			this.closemyself();
		}
	};
	window.closeToast = function() {
		$(".tankuang").remove();
	}

	// 方形loaading提示

	window.bigLoading = function(opt) {
		$("#myalert").remove();
		this.text = opt.text || '';
		this.timeout = opt.timeout || 0; //自动消失时间，单位毫秒
		this.opacity = opt.opacity || 0.52; //loading的背景透明度
		this.timer = null;
		this.init();
	}
	window.bigLoading.prototype = {
		init: function() {
			this.bg = this.text == '' ? $('<div id="myalert" class="myalert notext"></div>') : $('<div id="myalert" class="myalert"></div>');
			this.main = $('<div class="Tissuemain" style="background: rgba(0, 0, 0, '+this.opacity+');"><div class="TissueLoading"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div><p>' + this.text + '</p></div>');
			this.bg.append(this.main);
			$("body").append(this.bg);
			if(this.timeout > 0) {
				var that = this;
				this.timer = setTimeout(function() {
					that.destroy();
				}, this.timeout);
			}
		},
		destroy: function(callback) {
			var that = this;
			setTimeout(function() {
				that.bg.remove();
				if(callback&&callback instanceof Function){
					callback();
				}
			}, 50);

		}
	}

	// 滚动加载数据的loaading提示

	window.sLoading = function(opt) {
		$("#myalert,.TissueLoading").remove();
		this.text = opt.text || '';
		this.con = opt.con || 'body';
		this.timeout = opt.timeout || 0; //单位毫秒
		this.timer = null;
		this.init();
	}
	window.sLoading.prototype = {
		init: function() {
			this.con = this.con instanceof Object ? this.con : $(this.con);
			this.main = $('<div class="TissueLoading scrollLoading"><div class="spinner-container container1"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container2"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div><div class="spinner-container container3"><div class="circle1"></div><div class="circle2"></div><div class="circle3"></div><div class="circle4"></div></div></div>');
			this.con.append(this.main);
			if(this.timeout > 0) {
				var that = this;
				this.timer = setTimeout(function() {
					that.destroy();
				}, this.timeout);
			}
		},
		destroy: function(callback) {
			var that = this;
			setTimeout(function() {
				that.main.remove();
				if(callback&&callback instanceof Function){
					callback();
				}
			}, 50);
		}
	}

	// 统一ajax请求
	window.doAjax = function(url, data, success, error, complete, LoadingOpt, opt) {

		if( !url )
			return;

		LoadingOpt = LoadingOpt || null;
		if(LoadingOpt&&LoadingOpt.con){		
			var loading = new sLoading({
				con : LoadingOpt.con
			});
		}else{
			var loading = new bigLoading({});
        }
        
        // console.log(url,url instanceof Object ,url instanceof Array,url instanceof Function);

		if( url instanceof Object )
		{
			var ajaxOpt = url;

			if( url.success )
			{
				ajaxOpt.success = function(res) {
					loading.destroy(url.success(res));				
				};
			}
				

			if( url.error )
			{
				ajaxOpt.error = function(xhr, err, code) {
					loading.destroy(url.error(xhr, err, code));
				};
			}
				

			if( url.complete )
			{
				ajaxOpt.complete = function(res) {
					loading.destroy(url.complete(res));				
				};
			}
				
			ajaxOpt.timeout = url.timeout || 8000;
		}else {
			var ajaxOpt = {
				type: opt.type || 'post',
				url: url,
				dataType: opt.dataType || 'json',
				async: opt.async || true,
				timeout: opt.timeout || 8000,
				data: data,
				success: function(res) {
					loading.destroy(success(res));				
				},
				error: function(xhr, err, code) {				
					if(error && error instanceof Function) {
						loading.destroy(error(xhr, err, code));
					} else {
						loading.destroy();
						var newtoast = new Toast({
							title: "未知错误",
							content: "很抱歉，请您稍后重试。"
						})
					}
				},
				complete: function(xhr, err, code) {				
					if(complete && complete instanceof Function) {
						loading.destroy(complete(xhr, err, code));
					}
				}
			};
		}

		setTimeout(function() {
			$.ajax(ajaxOpt)
		}, 150);
	}

	// 滚动加载方法,支持多tab切换,以及绑定tab点击事件,程序内已经自动集成页数加载
	///* tab : [{
	//	obj: ".tab1",
	//	
	//	click: function(){
	//		
	//	}
	//}]
	//Api: ['api1','api2'],多tab相同时可只传一组
	//stepBottom: 距离底部开始加载数据的距离,默认 50
	//pagekey: 设置页码键名和初始键值[{key:"pageNum",initNum:1}],如果键值为1时将在初始化时自动加载一次数据,多tab相同时可只传一组
	//data 设置常规参数[{uid:'111',key:"www"}],多tab相同时可只传一组
	//success : 获取数据成功之后的回调函数
	//initIndex: 默认索引
	//*/
	window.ScollLoad = function(opt) {
		this.tabList = opt.tab instanceof Object ? opt.tab : '';
		this.Api = opt.Api && opt.Api instanceof Object ? opt.Api : '';
		this.stepBottom = opt.stepBottom || 50;
		this.data = opt.data && opt.data instanceof Object ? opt.data : [{}];
		this.pagekey = opt.pagekey && opt.pagekey instanceof Object ? opt.pagekey : [{
			key: "pageNum",
			initNum: 1
		}];
		this.success = opt.success instanceof Function ? opt.success : null;
		this.error = opt.error instanceof Function ? opt.error : null;
		this.complete = opt.complete instanceof Function ? opt.complete : null;
		this.initIndex = opt.initIndex || 0;
		this.LoadedData = [];
		this.Loadingcon = opt.Loadingcon || ['.post_list_con'];
		this.noDataTpl  = opt.noDataTpl  || ['<div class="ScollLoadDataTpl noDataTpl">还没有数据⊙▂⊙</div>'];
		this.noMoreDataTpl  = opt.noMoreDataTpl  || ['<div class="ScollLoadDataTpl noMoreDataTpl">没有更多了o(>_<)o ~~</div>'];
		if(this.tabList === '' || this.Api === '' || this.success === '') {
			var Tisue = new Toast({
				title: "错误",
				content: "ScollLoad配置错误"
			})
			return;
		}
		this.init();
	}
	window.ScollLoad.prototype = {
		init: function() {
			var that = this,
				tablength = this.tabList.length;
			for(var i = 0; i < tablength; i++) {
				that.LoadedData[i] = {};
				that.LoadedData[i].data = [];
				if(that.data.length < tablength) {
					that.data[i] = that.data[0];
				}
				if(that.Api.length < tablength) {
					that.Api[i] = that.Api[0];
				}
				if(that.pagekey.length < that.data.length) {
					that.pagekey[i] = that.pagekey[0];
				}
				if(that.Loadingcon.length < tablength) {
					that.Loadingcon[i] = that.Loadingcon[0];
				}
				if(that.noDataTpl.length < tablength) {
					that.noDataTpl[i] = that.noDataTpl[0];
				}
				if(that.noMoreDataTpl.length < tablength) {
					that.noMoreDataTpl[i] = that.noMoreDataTpl[0];
				}
				that.data[i][that.pagekey[i].key] = that.pagekey[i].initNum;
				that.tabList[i].scrolltop = document.scrollingElement.scrollTop || 0;
				that.tabList[i].scrollbody = that.tabList[i].scrollbody || window;
				that.tabList[i].isLoading = false;
				that.tabList[i].nomore = false;
				var obj = document.querySelector(this.tabList[i].obj) || null;
				if(obj) {
					obj.index = i;
					obj.onclick = function() {
						var index = this.index;
						if(that.tabList[index].click != undefined && that.tabList[index].click instanceof Function) {
							that.tabList[index].click();
						}
						that.tabList[index].scrolltop = document.scrollingElement.scrollTop || 0;
						that.initIndex = index;
						if(!that.LoadedData[index].data || that.LoadedData[index].data.length == 0) {
							that.loadData();
						}

					}
				}
				that.scroll(that.tabList[i].scrollbody);
			}
			if(that.pagekey[that.initIndex].initNum === 1) {
				console.log(that.pagekey[that.initIndex].initLoadData)
				if(that.pagekey[that.initIndex].initLoadData == undefined ||that.pagekey[that.initIndex].initLoadData){
					that.loadData();
				}			
			}		
		},
		loadData: function(callback) {
			console.log(this);
			var that = this;
			if(this.tabList[this.initIndex].nomore || this.tabList[this.initIndex].isLoading) {
				return;
			}
			var predata = this.LoadedData[that.initIndex].data[this.data[that.initIndex][that.pagekey[that.initIndex].key]-1] || null;
			if(predata){
				that.data[that.initIndex][that.pagekey[that.initIndex].key]++;
				if(callback&&callback instanceof Function){
					callback(predata);
				}
				this.success(predata);
				return;
			}
			this.tabList[this.initIndex].isLoading = true;
			
			var	success = function(res) {
					that.data[that.initIndex][that.pagekey[that.initIndex].key]++;
					that.LoadedData[that.initIndex].data.push(res);
					that.success(res);
				},
				url = that.Api[that.initIndex],
				data = that.data[that.initIndex],
				complete = function(res){
					if(that.complete){
						that.complete(res);
					}
					if(callback&&callback instanceof Function){
						callback(res);
					}
					that.tabList[that.initIndex].isLoading = false;
				};
			doAjax(url, data, success, this.error, complete, {con:that.Loadingcon[that.initIndex]});
		},
		setNodata:function(index){
			index = index || this.initIndex;
			this.tabList[index].nomore = true;
			if(this.noDataTpl[index] && this.noDataTpl[index]!=''){
				var con = document.querySelector(this.Loadingcon[index]),
					Nodes = parseDom(this.noDataTpl[index]);
				this.noDataTpl[index] = null;
				setTimeout(function(){
					for (var i = 0; i < Nodes.length; i++) {
						if(!Nodes[i].className || Nodes[i].className==''){
							Nodes[i].className = 'ScollLoadDataTpl noDataTpl';
						}					 
						if(!con.parentNode.querySelector('.'+Nodes[i].className.replace(/\s/g,'.'))){
							insertAfter(Nodes[i],con);
						}
					}
				}, 500)
				
			}

		},
		setNomore:function(index){
			index = index || this.initIndex;
			this.tabList[index].nomore = true;
			if(this.noMoreDataTpl[index] && this.noMoreDataTpl[index]!=''){
				var con = document.querySelector(this.Loadingcon[index]),
					Nodes = parseDom(this.noMoreDataTpl[index]);
				this.noMoreDataTpl[index] = null;
				setTimeout(function(){
					for (var i = 0; i < Nodes.length; i++) {
						if(!Nodes[i].className || Nodes[i].className==''){
							Nodes[i].className = 'ScollLoadDataTpl noMoreDataTpl';
						}					 
						if(!con.parentNode.querySelector('.'+Nodes[i].className.replace(/\s/g,'.'))){
							insertAfter(Nodes[i],con);
						}
					}
				},500);
			}
		},
		reSet:function(index,clearData){
			index = index || this.initIndex;
			this.tabList[index].isLoading = false;
			this.tabList[index].nomore = false;
			if(clearData&&clearData===true){
				this.LoadedData[index].data = [];
			}
			this.data[index][this.pagekey[index].key] = 1;
		},
		setData:function(index,key,data){
			index = !parseInt(index) || index === undefined || index === null || index === '' ?  this.initIndex : parseInt(index);
			if(!key || data === undefined || data === null){
				return;
			}
			index = index >= this.data.length ? this.data.length - 1 : index;
			index = index < 0 ? 0 : index;
			this.data[index][key] = data;
		},
		scroll: function(scrollbody) {
			scrollbody = scrollbody || window;
			var _this = this,
				step = _this.stepBottom,
				Oscrolltop = 0,
				scrolltop = 0,
				cliHeight = 0,
				docHeight = 0;
			_this.Regscroll = true;
			scrollbody = scrollbody instanceof Object ? scrollbody : document.querySelector(scrollbody);
			if(scrollbody === window || scrollbody === document){
				scrollbody.onscroll = function() {
					scrolltop = window.pageYOffset || window.document.documentElement.scrollTop || window.document.body.scrollTop;
					cliHeight = window.innerHeight || document.documentElement.clientHeight;
					docHeight = document.body.offsetHeight || document.documentElement.offsetHeight;
					if(docHeight - step < scrolltop + cliHeight && scrolltop > Oscrolltop) {
						_this.loadData();
					}
					Oscrolltop = scrolltop;
					_this.tabList[_this.initIndex].scrolltop = scrolltop;
				};
			}else{
				scrollbody.onscroll = function() {
					scrolltop = scrollbody.scrollTop || 0;
					cliHeight = scrollbody.clientHeight || window.innerHeight || document.documentElement.clientHeight;
					docHeight = scrollbody.scrollHeight || document.documentElement.offsetHeight;
					if(docHeight - step < scrolltop + cliHeight && scrolltop > Oscrolltop) {
						_this.loadData();
					}
					Oscrolltop = scrolltop;
					_this.tabList[_this.initIndex].scrolltop = scrolltop;
				};
			}
			
		}
	}
	// animate
	window.Animate = function(opt){
		if(!opt || !opt instanceof Object || !opt.callback || !opt.callback instanceof Function){
			return;
		}
		var _this = this;
		_this.start 	= parseInt(opt.start) || 0;
		_this.end 		= parseInt(opt.end) || 1;
		_this.animate 	= parseInt(opt.animate) || 200;
		_this.callback 	= opt.callback;
		_this.interval  = opt.interval || 20;
		_this.init();
	}
	window.Animate.prototype = {
		init: function(){
			var _this = this;
			_this.dirt_times 	= Math.ceil(_this.animate/_this.interval);
			_this.dirt_val 	= _this.end - _this.start;
			_this.dirt_change =  parseFloat((_this.dirt_val / _this.dirt_times).toFixed(3));
			_this.runTimes 	= 0;
			if(!_this.dirt_val || _this.dirt_val == 0){
				return;
			}
			_this.Run();
		},
		Run: function(){
			var _this = this;
			var timer = setInterval(function(){
				_this.runTimes = _this.runTimes < _this.dirt_times ? _this.runTimes + 1 : _this.dirt_times;
				_this.callback(_this.start+(_this.dirt_change*_this.runTimes));
			}, _this.interval);
			_this.destroy(timer);
		},
		destroy:function(timer){
			var _this = this;
			setTimeout(function(){
				clearInterval(timer);
			},_this.animate+(_this.interval*3));
		}
	}
	// 滚动到指定的高度
	window.scrollTo = function(opt){
		var _this = {};
		_this.opt = opt || null;
		if(!_this.opt || _this.opt.obj == ''){
			return;
		}
		_this.opt.obj = _this.opt.obj || 'body';
		var top = _this.opt.top || 0,
			obj = typeof _this.opt.obj === 'object' ?  _this.opt.obj : document.querySelector(_this.opt.obj),
			animate = _this.opt.animate || 0;
		var nowTop = obj.scrollTop || 0,
			dirt_top = Math.abs(nowTop - top);
		if(dirt_top<2){
			return;
		}
		if(typeof animate != 'number' || animate<0){
			animate = 0;
		}
		if(animate < 20){
			obj.scrollTop = top;
			return;
		}
		var _animation = new Animate({
			start: nowTop,
			end: top,
			animate: animate,
			callback: function(res){
				obj.scrollTop = res;
			}
		})
	}

	// 查看大图
	window.ViewImg = function(opt) {
		if(!Swiper || Swiper === undefined){
			var tisi = new Toast({
				title: '错误',
				content: '查看大图依赖Swiper未安装'
			});
			return;
		}
		opt = opt || {};
		this.init(opt);
	}
	window.ViewImg.prototype = {
		init: function(opt) {
			var that = this;
			that.main = opt.main || $("body");
			that.imgCon = opt.imgCon || 'priviewImg';
			that.imgcls = opt.imgcls || '';
			that.imgsrc = opt.imgsrc || 'src';
			that.list = opt.list || [];
			that.show = opt.show || true;
			that.item = opt.item || 0;
			that.CloseModel = opt.CloseModel || 1;//关闭模式 0和text表示按照头部取消文字关闭，1和background表示点击背景层关闭
			var imgs = that.imgcls == '' ? that.main.find('img') : that.main.find('img.' + that.imgcls);
			if(imgs.length > 0) {
				for(var i = 0; i < imgs.length; i++) {
					var src = $(imgs[i]).attr(that.imgsrc);
					that.list.push(src)
				}
				that.Render();
			}
			console.log(that);
		},	
		Render: function() {
			var that = this,
				list = '<div class="swiper-container"><ul class="swiper-wrapper">';
			that.previewMenu = (that.CloseModel == 1 || that.CloseModel == 'background') ? $('<div class="topHeader" style = "display:none;"></div>') : $('<div class="topHeader"></div>');
			that.preview = $('<div class="'+that.imgCon+'"></div>');
			that.previewCancel = $('<button class="closePri" >取消</button>');
			if(!/^[0-9]*$/.test(that.item)) {
				for(var i = 0; i < that.list.length; i++) {
					list += '<li class="swiper-slide"><img data-src="'+ that.list[i] +'" class="swiper-lazy" style="max-height:100%;max-width:100%;"><div class="swiper-lazy-preloader"></div></li>';
					that.item = that.item == that.list[i] ? i : that.item;
				}
			} else {
				for(var i = 0; i < that.list.length; i++) {
					list += '<li class="swiper-slide"><img data-src="'+ that.list[i] +'" class="swiper-lazy" style="max-height:100%;max-width:100%;"><div class="swiper-lazy-preloader"></div></li>';
				}
			}
			if(that.CloseModel == 1 || that.CloseModel == 'background'){
				that.preview.click(function(){
					that.close();
				});
				that.preview.find("img").click(function(e){
					e.stopPropagation();
				});
			}
			that.previewCancel.click(function() {
				that.close();
			})
			that.previewMenu.append(that.previewCancel);
			that.preview.html('').append(that.previewMenu).append(list + '</ul></div>');
			if($("body").find("."+that.imgCon.replace(/\s/g,'.')).length > 0) {
				$("."+that.imgCon.replace(/\s/g,'.')).remove();
				$("body").append(that.preview);
			}else{
				$("body").append(that.preview);
			}

			if(!/^[0-9]*$/.test(that.item)) {
				that.item = 0;
			}

			that.preview.show();
			that.mySwiper = new Swiper('.swiper-container', {
				direction: 'horizontal',
				initialSlide: that.item,
				slidesPerView: 1,
				zoom: true,
				lazyLoading : true,
				spaceBetween: 20
			});
		},
		setItem: function(data) {
			var that = this;
			if(!/^[0-9]*$/.test(data)) {
				for(var i = 0; i < that.list.length; i++) {
					that.item = data == that.list[i] ? i : that.item;
				}
			} else if(data > that.list.length - 1) {
				that.item = that.list.length - 1;
			} else {
				that.item = data;
			}
			console.log(that.item);
			that.mySwiper.slideTo(that.item, 500, false); //切换到第一个slide，速度为0.5秒
		},
		view: function() {
			this.preview.show();
		},
		close: function() {
			this.preview.hide();
		},
		destroy: function() {
			this.preview.remove();
		}
	}

	// 视频播放
	window.ViewVideo = function(opt){
		this.opt = opt || {};
		this.opt.obj = this.opt.obj || null;
		this.opt.Vurl = this.opt.Vurl || 'data-src';
		this.opt.Purl = this.opt.Purl || 'src';
		if(!this.opt.obj){
			return;
		}
		this.init();
	}
	window.ViewVideo.prototype = {
		init:function(){
			var _this = this,obj = _this.opt.obj;
			if(obj){
				var Vurl = obj.getAttribute(_this.opt.Vurl) || '',
					Purl = obj.getAttribute(_this.opt.Purl) || '';
				if(Vurl!='' && Purl!=''){
					var bg = document.createElement("div"),
						Closebtn = document.createElement("div"),
						iframe = document.createElement("iframe");
					bg.className = 'VideoPreview img-preview';
					bg.style.opacity = '1';
					bg.style.display = 'block';
					Closebtn.className = 'Video_close fanhui';
					iframe.className = 'Video_iframe';
					iframe.style.position = 'absolute';
					iframe.style.width = '100%';
					iframe.style.height = '100%';
					iframe.style.border = 'none';
					iframe.setAttribute("src", 'https://apps.fenhol.com/html5/index/video?vurl='+Vurl+'&murl='+Purl);
					bg.appendChild(Closebtn);
					bg.appendChild(iframe);
					document.querySelector("body").appendChild(bg);
					Closebtn.click = function(){
						_this.destroy(bg);
					}
				}
			}
		},
		destroy:function(obj){
			obj.remove();
		}
	}


	// 图片懒加载
	window.LayzyLoad = function(opt){
		this.opt = opt || {};
		this.opt.imgcls = this.opt.imgcls || null;
		this.opt.imgsrc = this.opt.imgsrc || "_src";
		this.opt.fadeIn = this.opt.fadeIn || 200;
		this.opt.opacityStart = parseFloat(this.opt.opacityStart) || 0;
		this.opt.opacityEnd = parseFloat(this.opt.opacityStart) || 1;
		this.opt.preview = this.opt.preview || 'https://dist.fenhol.com/App/img/background/layzyLoadbg.jpg';
		this.opt.preshow = parseInt(this.opt.preshow) || 1;
		this.scrollBody = this.opt.scrollBody || "body";
		this.initTimer = null;
		this.list = [];
		this.init();
	}

	window.LayzyLoad.prototype = {
		init: function(){
			var _this = this;
			_this.ClientY = window.innerHeight;
			_this.scrollBody = typeof _this.scrollBody == Object ? _this.scrollBody : document.querySelector(_this.scrollBody); 
			_this.selectorStr = !_this.opt.imgcls || _this.opt.imgcls == '' ? 'img['+_this.opt.imgsrc+'^=http]' : _this.opt.imgcls+'['+_this.opt.imgsrc+'^=http]';
			_this.initTimer = setInterval(function(){
				_this.selector(0);
			},100);
			
			// var style = '<style>'+_this.selectorStr+'{opacity:'+_this.opt.opacityStart+';transition-duration:'++'}</style>';
			// document.querySelector("style").innerHTML +=
			document.addEventListener("scroll",function(){
				_this.selector();
			})
		},
		selector: function(){
			var _this= this,
				top = _this.scrollBody.scrollTop || 0;		
			_this.list = document.querySelectorAll(_this.selectorStr);
			// if(_this.list.length > 0 && _this.initTimer){
			// 	clearInterval(_this.initTimer);
			// 	_this.initTimer = null;
			// }
			for (var i = 0; i < _this.list.length; i++) {
				var obj = _this.list[i],
					absTop = getAbsTop(obj);
				if(absTop > (top - obj.offsetHeight - 50*_this.opt.preshow) && absTop < (top + _this.ClientY + 50 * _this.opt.preshow)){
					// 图片在区域内
					_this.Render(obj);
				}
			}		
		},
		Render:function(obj){
			var _this = this,
				src = obj.getAttribute(_this.opt.imgsrc) || '';
				if(_this.opt.preview&&/^http/.test(_this.opt.preview)){
					obj.setAttribute("src", _this.opt.preview);
				}
				obj.style.opacity = _this.opt.opacityStart;
				obj.style.transitionDuration  = _this.opt.fadeIn/1000 + 's';
				obj.removeAttribute(_this.opt.imgsrc);
			if(src!=''){
				var image = new Image();
				image.src = src;
				image.onload = function(){
					obj.setAttribute("src", src);
					if(_this.opt.fadeIn>0){
						_this.fadeIn(obj);
					}
				}
			}

		},
		fadeIn:function(obj){
			var _this = this;		
			obj.style.opacity = _this.opt.opacityEnd;		
		}
	};
	// 获取元素相对与文档绝对纵坐标
	window.getAbsTop = function(e){
		var offset=e.offsetTop; 
		if(e.offsetParent!=null) offset+=getAbsTop(e.offsetParent); 
		return offset; 
	}
	// 获取元素相对与文档绝对横坐标
	window.getAbsLeft = function(e){ 
		var offset=e.offsetLeft; 
		if(e.offsetParent!=null) offset+=getAbsLeft(e.offsetParent); 
		return offset; 
	}

	// 倒计时(正计时)
	window.Countdown = function(opt) {
	    this.totalTime = opt.totalTime || 60; //总时间
	    this.model = opt.model || "reduce"; // 计时方式（reduce倒计时、plus正计时）
	    this.speed = opt.speed || 50; // 刷新速度 默认50毫秒一次
	    this.setSec = opt.setSec || false; // 计时结果取秒
	    this.start_callback = opt.start_callback || function() {}; // 计时开始回调函数
	    this.callback = opt.callback || function() {}; // 计时中回调函数
	    this.end_callback = opt.end_callback || function() {}; // 结束时回调函数

	    this.init();
	}
	window.Countdown.prototype = {
	    init: function() {
	      var dateTime = new Date();
	      this.start = dateTime.getTime();
	      this.dirt = this.totalTime;
	      this.start_callback();
	      if("reduce" == this.model) {
	        this.timer();
	      } else {
	        this.timer_plus();
	      }

	    },
	    timer: function() {

	      var _this = this;
	      this.the_timer = setInterval(function() {
	        var now = new Date();

	        if(_this.setSec) {
	          _this.dirt = _this.totalTime - (Math.round((now.getTime() - _this.start) / 1000));
	        } else {
	          _this.dirt = _this.totalTime - now.getTime() + _this.start;
	        }

	        _this.callback(_this.dirt);

	        if(0 >= _this.dirt) {
	          clearInterval(_this.the_timer);
	          _this.end_callback();
	        }

	      }, this.speed);
	    },
	    timer_plus: function() {
	      var _this = this;
	      this.the_timer = setInterval(function() {
	        var now = new Date();

	        if(_this.setSec) {
	          _this.dirt = Math.round((now.getTime() - _this.start) / 1000);
	        } else {
	          _this.dirt = now.getTime() - _this.start;
	        }

	        _this.callback(_this.dirt);

	        if(_this.totalTime <= _this.dirt) {
	          clearInterval(_this.the_timer);
	          _this.end_callback();
	        }

	      }, this.speed);
	    }

	}

	/**
	* 页码生成类
	*/ 
	window.Page = function( opt )
	{
	    this.total = parseInt( opt.total ) || 1;// 总页数
	    this.initPage = parseInt(opt.initPage) || 1;//初始页数
	    this.perNum = parseInt(opt.perNum) || 5;// 显示几个页码
	    this.lastFirst = opt.lastFirst || false;//是否显示第一页和最后一页按钮
	    this.con = opt.con || "#pageCon"; // 渲染的容器
	    this.firstBtn = opt.firstBtn || '<span><span>«</span></span>'; // firstBtn html
	    this.lastBtn = opt.lastBtn || '<span><span>»</span></span>'; // lastBtn html
	    this.callback = opt.callback || function(){};// 点击的回调
	    this.init();
	}

	window.Page.prototype = {
	    init: function(){
	        if( 2 > this.total )
	            return;

	        this.con = this.con instanceof Object ? this.con : document.querySelector(this.con);
	        this.render();
	    },
	    setTotal: function( total )
	    {
	        this.total = parseInt(total);
	    },
	    setInitPage: function( initPage )
	    {
	        this.initPage = parseInt(initPage);
	    },
	    render: function()
	    {
	        var _this = this;
	        _this.container = document.createElement("ul");
	        _this.container.setAttribute( "class", "pagination" );
	        _this.buildBody();
	        _this.con.innerHTML = '';
	        _this.con.appendChild(_this.container);
	    },
	    buildBody: function()
	    {
	        var html = '',_this = this;           

	        // 计算起止点
	        if( _this.perNum < _this.total )
	        {
	            var avar = parseInt( _this.perNum/2 );
	            var start = _this.initPage - avar;
	            var end = _this.initPage + avar;

	            if( 1 > start )
	            {
	                start = 1;
	                end = start + _this.perNum;
	            }else if( _this.total < end )
	            {
	                end = _this.total;
	                start = end - _this.perNum;
	            }                

	        }else{
	            var start = 1,end = _this.total;
	        }
	        
	        _this.buildFirst(start,end);

	        for (var pageNum = start; pageNum <= end; pageNum++) {
	            var dom = document.createElement("li");
	            if( this.initPage == pageNum )
	                dom.setAttribute("class", "active");

	            dom.innerHTML = '<span>'+ pageNum +'</span>';
	            dom.pageIndex =  pageNum;

	            dom.onclick = function(){
	                if( this.pageIndex == _this.initPage )
	                {
	                    return;
	                }
	                _this.initPage = this.pageIndex;
	                _this.callback(this.pageIndex);
	                _this.render();
	            }
	            _this.container.appendChild(dom);
	        }
	        _this.buildLast(start,end);
	    },
	    buildFirst: function(start,end)
	    {
	        if( !this.lastFirst )
	            return;

	        var _this = this;

	        if( 1 < start )
	        {
	            var dom = document.createElement("li");
	                dom.innerHTML = _this.firstBtn;
	            dom.onclick = function( ){
	                if( 1 == _this.initPage )
	                {
	                    return;
	                }
	                _this.initPage = 1;
	                _this.callback(1);
	                _this.render();
	            }
	            _this.container.appendChild(dom);
	        }

	    },
	    buildLast: function(start,end)
	    {
	        if( !this.lastFirst )
	            return;

	        var _this = this;

	        if( _this.total > end )
	        {
	            var dom = document.createElement("li");
	                dom.innerHTML = _this.lastBtn;
	            dom.onclick = function( ){
	                if( _this.total == _this.initPage )
	                {
	                    return;
	                }
	                _this.initPage = _this.total;
	                _this.callback(_this.total);
	                _this.render();
	            }
	            _this.container.appendChild(dom);
	        }

	    }

	}

	// 检查手机号
	window.chkTel = function ( str )
	{
		var reg =/^(1(([358][0-9])|[4][56789]|[7][0135678]|[9][89]|[6][6]))\d{8}$/;
		if( reg.test(str) )
			return true;
		return false;
	}

	// ip转数字
	window.ip2long = function (ip){
		var REG =/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/;
	    var xH = "",result = REG.exec(ip);
	    if(!result) return -1;
	    return (parseInt(result[1]) << 24 
	        | parseInt(result[2]) << 16
	        | parseInt(result[3]) << 8
	        | parseInt(result[4]))>>>0;
	}

	// 数字转ip
	window.long2ip = function (INT){
	    if(INT < 0 || INT > 0xFFFFFFFF){
	        throw ("The number is not normal!");
	    }
	    return (INT>>>24) + "." + (INT>>16 & 0xFF) + "." + (INT>>8 & 0xFF) + "." + (INT & 0xFF);
	}

	//表情转文字,上传图片转指定格式
	window.Emoji2txt = function(str) {
		str = str || '';
		str = str.replace(/<img[\s\S^>]*? class\=\"tsingcupload[\s\w\W^\"]*?\" src\=\"([^\s^>]*?)\" alt\=\"([\w\W^>]*?)\" owidth\=\"([0-9]*)\" oheight\=\"([0-9]*)\".*?\>/gi, 'tsingcimg_{url:$1,alt:$2,owidth:$3,oheight:$4}');
		str = str.replace(/<img[\s\S^>]*? class\=\"tsingcemotion\" src\=\"https\:\/\/dist\.fenhol\.com\/emotions\/([^\s^\/]*?)\/([\d]*?)\.gif".*?\>/gi, 'em_{id:$2,label:$1}');
		return str;
	}
	//插入的网易音乐转文字
	window.Music2txt = function(str) {
		str = str || '';
		//str = str.replace(/<iframe[\s\S^>]*? class="musiciframe" src="([^\s]*?)".*?\>\<\/iframe>/gi, '[music_$1]');
		str = str.replace(/<iframe[\s\S^>]*? class="musiciframe" src="[^\"^\s]*?\id\=([0-9]*).*?" mname="([\w\W]*?)" singer="([\w\W]*?)".*?\>\<\/iframe>/gi, 'wymusic_{mid:$1,name:$2,singer:$3}');
		return str;
	}
	//视频转文字
	window.Video2txt = function(str) {
		str = str || '';
		return str;
	}
	//过滤没有指定内容的img、iframe标签
	window.Imgfilter = function(str) {
		str = str || '';
		str = str.replace(/<img[\s\S^>]*?.*?\>/gi, '');
		str = str.replace(/<ifame[\s\S^>]*?.*?\>/gi, '');
		return str;
	}
	//@格式转换为文字
	window.At2txt = function(str) {
		str = str || '';
		str = str.replace(/<a[\s\S^>]*? class="atwho-added" uid="([\d]*?)" uname="([\w\W]*?)"\>.+?\<\/a\>/gi, 'at_{uid:$1,uname:$2}');
		return str;
	}
	//表情、音频、视频统一转为文字
	window.Html2txt = function(str) {
		str = Emoji2txt(str);
		str = Music2txt(str);
		str = Video2txt(str);
		str = Imgfilter(str);
		str = At2txt(str);
		str = str.replace(/\r\n/g,"<br>")    
	    str = str.replace(/\n/g,"<br>");    
		return str;
	}
	//文字转为表情、音乐、视频
	window.Txt2html = function(str, fnName) {
		fnName = fnName || '';
		str = str || '';
		var showpic = fnName + 'PreviewImageView',
			showuser = fnName + 'showPersonPage',
			showvideo = fnName + 'playVideo';
		//表情转化
		str = str.replace(/\[em\_([\d]{1,3})\]/gi, '<img class="tsingcemotion" src="https://dist.fenhol.com/emotions/default/$1.gif"/>');
		str = str.replace(/em\_\{id\:([\d]*?)\,label\:([^\s]*?)\}/gi, '<img class="tsingcemotion" src="https://dist.fenhol.com/emotions/$2/$1.gif"/>');
		//上传的图片转化
		str = str.replace(/tsingcimg\_\{url\:([^\s]*?)\,alt\:([\w\W]*?)\,owidth\:([\d]*?)\,oheight\:([\d]*?)\}(\<br[\/]*?\>){0,1}/gi, '<img class="tsingcupload" _src="$1?x-oss-process=style/w_750" onclick="' + showpic + '(\'$1\')" alt="$2" owidth="$3" oheight="$4"/>');
		//str = str.replace(/tsingcimg\_\{url\:([^\s]*?)\,alt\:([\w\W]*?)\,owidth\:([\d]*?)\,oheight\:([\d]*?)\}/gi, '<img class="tsingcupload" _src="$1?x-oss-process=style/w_750" onclick="' + showpic + '(\'$1\')" alt="$2" owidth="$3" oheight="$4"/>');
		//视频转换
		str = str.replace(/tsingcvideo\_\{url\:([^\s]*?)\,title\:([\w\W]*?)\,pic\:([\w\W]*?)\}\<br[\/]*?\>/gi, '<div class="tsingcvideo" style="background-image:url($3)" onclick="' + showvideo + '(\'$3\',\'$1\')" video="$1" title="$2"><i></i></div>');
		str = str.replace(/tsingcvideo\_\{url\:([^\s]*?)\,title\:([\w\W]*?)\,pic\:([\w\W]*?)\}/gi, '<div class="tsingcvideo" style="background-image:url($3)" onclick="' + showvideo + '(\'$3\',\'$1\')" video="$1" title="$2"><i></i></div>');
		//音乐转换
		str = str.replace(/wymusic\_\{mid\:([\d]*?)\,name\:([\w\W]*?)\,singer\:([\w\W]*?)\}\<br[\/]*?\>/gi, '<iframe class="musiciframe" src="http://music.163.com/outchain/player?type=2&id=$1&auto=0"></iframe>');
		str = str.replace(/wymusic\_\{mid\:([\d]*?)\,name\:([\w\W]*?)\,singer\:([\w\W]*?)\}/gi, '<iframe class="musiciframe" src="http://music.163.com/outchain/player?type=2&id=$1&auto=0"></iframe>');
		//@格式转换
		str = str.replace(/at\_\{uid\:([\d]*?)\,uname\:([\w\W]*?)\}/gi, '<a class="atwho-added" uid="$1" alt="$2" onclick="' + showuser + '(\'$1\')">@$2</a>');
		//超链接转换
		str = str.replace(/<a[\s\S^>]*? class=\"tsingclink\" link=\"([^\s]*?)\".*?\>([\w\W]*?)\<\/a\>/gi, '<a class="tsingclink" href="$1" target="_blank">$2</a>');
		// 换行
		str = str.replace(/\\r\\n/g, "<br/>");
		return str;
	}

	window.isIOS = function()
	{
		if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {
		  return true;
		} else {
			return false;
		}  
	}

	window.H5PreviewImageView = function(url){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.PreviewImageView.postMessage([url]);

	};
	window.H5showPersonPage = function(uid){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation(); 
		window.webkit.messageHandlers.showPersonPage.postMessage([uid]);		
	};
	window.H5playVideo = function(img,url){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.playVideo.postMessage([img,url]);		
	};
	window.H5locationUrl = function(url,rid,floor,uname){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.locationUrl.postMessage([url,rid,floor,uname]);		
	};
	window.H5replyTo = function(uid,uname,reid){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.replyTo.postMessage([uid,uname,reid]);		
	};
	window.H5showMenu = function(type,objid){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.showMenu.postMessage([type,objid]);		
	};
	window.H5doHire = function(uid){
		window.event?window.event.cancelBubble=true:window.event.stopPropagation();
		window.webkit.messageHandlers.doHire.postMessage([uid]);
	};
})(window);
// 自动实例化获取参数
window.UrlParam = new UrlParse();